let http = require('http')
let fs = require('fs').promises
let url = require('url')
let server = http.createServer((req, res) => {
  // console.log(req)
  res.setHeader("www", "777") //设置响应头
  let obj = url.parse(req.url, true)
  // console.log(obj)
  if (obj.pathname == '/') {
    fs.readFile('./page/index.html').then(data => {
      res.end(data)
    })
  } else if (obj.pathname == '/favicon.ico') {
    fs.readFile('./page/favicon.ico').then(data => {
      res.end(data)
    })
  } else if (obj.pathname == '/list') {
    let str = '';
    req.on('data', chunk => {
      // console.log('chunk', chunk);
      str += chunk
    })
    req.on('end', () => {
      console.log('str:', str)
      fs.readFile('./data.json').then(data => {
        data = data.toString()
        data = JSON.parse(data)
        data.push(JSON.parse(str))
        fs.writeFile('./data.json', JSON.stringify(data)).then(d => {
          res.end(JSON.stringify(data))
        })

      })
    })

  } else {
    res.end('hahah')
  }


})
server.listen(8086, () => {
  console.log('ok');
})